//
//  NSMutableDictionary+ZXAvoidCrash.m
//  ZXAvoidCrash
//
//  Created by 朱新明 on 2023/3/14.
//

#import "NSMutableDictionary+ZXAvoidCrash.h"
#import "ZXAvoidCrashRuntime.h"
#import "ZXAvoidCrashReport.h"

@implementation NSMutableDictionary (ZXAvoidCrash)
+ (void)zx_avoidCrashExchangeMethod {
    
    Class __NSDictionaryM = NSClassFromString(@"__NSDictionaryM");
    
    [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:__NSDictionaryM originalSelector:@selector(setObject:forKey:) swizzledSelector:@selector(zx_avoidCrashSetObject:forKey:)];
    
    [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:__NSDictionaryM originalSelector:@selector(setObject:forKeyedSubscript:) swizzledSelector:@selector(zx_avoidCrashSetObject:forKeyedSubscript:)];
    
    [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:__NSDictionaryM originalSelector:@selector(removeObjectForKey:) swizzledSelector:@selector(zx_avoidCrashRemoveObjectForKey:)];
}



#pragma mark - setObject:forKey:
//=================================================================
//  setObject:forKey:
//  setObject: forKeyedSubscript:
//=================================================================
/*
崩溃：-[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: key2)
 */

- (void)zx_avoidCrashSetObject:(id)anObject forKey:(id<NSCopying>)aKey
{
    @try {
        [self zx_avoidCrashSetObject:anObject forKey:aKey];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception];
    } @finally {
        
    }
}



///*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKeyedSubscript:]: key cannot be nil'

- (void)zx_avoidCrashSetObject:(id)anObject forKeyedSubscript:(id<NSCopying>)aKey
{
    @try {
        [self zx_avoidCrashSetObject:anObject forKeyedSubscript:aKey];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception];
    } @finally {
        
    }
}


#pragma mark - removeObjectForKey:
//=================================================================
//  removeObjectForKey:
//
// 崩溃：-[__NSDictionaryM removeObjectForKey:]: key cannot be nil
//======================

- (void)zx_avoidCrashRemoveObjectForKey:(id<NSCopying>)aKey{
    @try {
        [self zx_avoidCrashRemoveObjectForKey:aKey];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception];
    } @finally {
        
    }
}
@end
